#include "AssetObjectSerializer.h"
#include "Object/FindObject.h"

CString CAssetObjectSerializer::SerializeToString(RObject *InObject)
{
    if(!InObject)
    {
        return U"null";
    }

    for(int32_t i=0;i<AssetHead.ExternalObjects.Num();i++)
    {
        if(AssetHead.ExternalObjects[i]==InObject->GetPath())
        {
            return U"External:"+CString(i);
        }
    }

    for(int32_t i=0;i<AssetHead.InternalObjects.Num();i++)
    {
        if(AssetHead.InternalObjects[i]==InObject->GetPath())
        {
            return U"Internal:"+CString(i);
        }
    }

    assert(false && "Object not found");
    return U"null";
}

TSharedObjectPtr<RObject> CAssetObjectSerializer::DeserializeFromString(const CString &InString)
{
    if(InString==U"null")
    {
        return nullptr;
    }

    if(InString.StartsWith(U"External:"))
    {
        int32_t Index=InString.SubString(9).ToInt64();
        assert(Index>=0 && Index<AssetHead.ExternalObjects.Num() && "Index out of range");
        auto Object= FindObject(AssetHead.ExternalObjects[Index]);
        assert(Object && "Object not found");
        return Object;
    }
    
    if(InString.StartsWith(U"Internal:"))
    {
        int32_t Index=InString.SubString(9).ToInt64();
        assert(Index>=0 && Index<AssetHead.InternalObjects.Num() && "Index out of range");
        auto& ObjectPath=AssetHead.InternalObjects[Index];
        auto Object= FindObject(ObjectPath);
        assert(Object && "Object not found");
        return Object;
    }
    
    
    assert(false && "Invalid string");
    return nullptr;
    
}
